package com.kate.mall.product.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 新梦想.陈超
 * @version 2021.2
 * @Description: {TODO}
 * @date 2023/3/13 下午2:46
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class Json2StringTypeHandler extends BaseTypeHandler<String[]> {
    //spring mvc内部集成json框架：jackson,的转换对象
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        ps.setString(i,object2String(strings));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return string2Object(rs.getString(columnName));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return string2Object(rs.getString(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return string2Object(cs.getString(columnIndex));
    }
    //方法1:json字符串数组--->字符串
    public String object2String(String[] obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //方法2:字符串--->json字符串数组
    public String[] string2Object(String value){
        try {
            return objectMapper.readValue(value,String[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
